package com.woniuxy.mini;

import com.woniuxy.core.service.AllUserService;
import com.woniuxy.core.service.SocialRelationshipService;
import com.woniuxy.core.service.UserStatsService;
import com.woniuxy.entity.AllUser;
import com.woniuxy.entity.DTO.UserInfoDTO;
import com.woniuxy.entity.SocialRelationship;
import com.woniuxy.entity.UserStats;
import com.woniuxy.entity.UserCoupon;
import com.woniuxy.util.ResponseData;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * @ClassName AllUserController
 * @Description
 * @Author nanqiao
 * @Date 2025/7/11 9:57
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class AllUserController {
    @Autowired
    private AllUserService allUserService;

    private final SocialRelationshipService socialRelationshipService;

    private final UserStatsService userStatsService;

    /**
     * 查询所有用户
     */
    @GetMapping("/all")
    public ResponseData<AllUser> getAllUsers() {
        return ResponseData.ok(allUserService.list());
    }

    /**
     * 根据ID查询用户详情
     */
    @GetMapping("/{userId}")
    public ResponseData<AllUser> getUserById(@PathVariable("userId") Long userId) {
        AllUser user = allUserService.getById(userId);
        if (user == null) {
            return ResponseData.fail(404, "用户未找到");
        }
        return ResponseData.ok(user);
    }

    /**
     * 新增用户
     */
    @PostMapping
    public ResponseData<Boolean> createUser(@RequestBody AllUser user) {
        boolean isSaved = allUserService.save(user);
        return isSaved ? ResponseData.ok(true) : ResponseData.fail(500, "保存失败");
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{userId}")
    public ResponseData<Boolean> updateUser(@PathVariable Long userId,
                                            @RequestBody AllUser user) {
        user.setUserId(userId); // 确保ID一致
        boolean isUpdated = allUserService.updateById(user);
        return isUpdated ? ResponseData.ok(true) : ResponseData.fail(500, "更新失败");
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}")
    public ResponseData<Boolean> deleteUser(@PathVariable Long userId) {
        boolean isDeleted = allUserService.removeById(userId);
        return isDeleted ? ResponseData.ok(true) : ResponseData.fail(500, "删除失败");
    }
    /**
     * 判断用户是否已关注目标用户
     *
     * @return true 已关注，false 未关注
     */
    @PostMapping("/isFollowed") // 改为POST
    public ResponseData<Boolean> isUserFollowed(@RequestBody SocialRelationship dto) { // 用@RequestBody接收
        boolean isFollowed = socialRelationshipService.isUserFollowed(dto.getUserId(), dto.getTargetId());
        return ResponseData.ok(isFollowed);
    }

    /**
     * 关注用户
     *
     * @return 关注结果
     */
    @PostMapping("/follow")
    public ResponseData followUser(@RequestBody SocialRelationship dto) {
        Long userId = dto.getUserId();
        Long targetId = dto.getTargetId();

        try {
            socialRelationshipService.followUser(userId, targetId);
        } catch (Exception e) {
            return ResponseData.fail(500, e.getMessage());
        }

        return ResponseData.ok();
    }


    /**
     * 取消关注用户
     */
    @PostMapping("/unfollow")
    public ResponseData unfollowUser(@RequestBody SocialRelationship dto) {
        Long userId = dto.getUserId();
        Long targetId = dto.getTargetId();

        try {
            socialRelationshipService.unfollowUser(userId, targetId);
        } catch (Exception e) {
            return ResponseData.fail(500, e.getMessage());
        }

        return ResponseData.ok();
    }

    /**
     * 获取用户信息（包含统计信息）
     *
     * @param userId 用户ID
     * @return 用户信息（包含统计信息）
     */
    @GetMapping("/info/{userId}")
    public ResponseData<UserInfoDTO> getUserInfo(@PathVariable("userId") Long userId) {

        // 获取用户基础信息
        AllUser allUser = allUserService.getById(userId);
        if (allUser == null) {
            return ResponseData.fail(404, "用户未找到");
        }

        // 换为UserInfoDTO（复制基础字段）
        UserInfoDTO userInfo = new UserInfoDTO();
        BeanUtils.copyProperties(allUser, userInfo);

        // 获取统计信息（关注数、粉丝数、获赞数、帖子数）
        UserStats userStats = userStatsService.getUserStatsByUserId(userId);
        if (userStats != null) {
            userInfo.setFollowCount(userStats.getFollowCount());
            userInfo.setFanCount(userStats.getFanCount());
            userInfo.setLikeCount(userStats.getLikeCount());
            userInfo.setPostCount(userStats.getPostCount());
        } else {
            // 统计信息不存在时设为0
            userInfo.setFollowCount(0L);
            userInfo.setFanCount(0L);
            userInfo.setLikeCount(0L);
            userInfo.setPostCount(0L);
            log.error("不该存在的错误: 用户的统计信息不存在，用户ID：{}", userId);
        }

        // 4. 获取互关数
        Long mutualFollowCount = socialRelationshipService.countMutualFollow(userId.intValue());
        userInfo.setMutualFollowCount(mutualFollowCount);

        return ResponseData.ok(userInfo);
    }

    /**
     * 获取优惠卷
     *
     * @param couponId 下单时选择的优惠卷 ID
     * @return userCoupon  优惠卷对象
     */
    @GetMapping("/coupon/{couponId}")
    public UserCoupon getCoupon(@PathVariable("couponId") Integer couponId) {
        return allUserService.getCoupon(couponId);
    }

    /**
     * 锁定优惠卷
     *
     * @param couponId 优惠卷 ID
     * @return 锁定结果
     */
    @PostMapping("/lockCoupon/{id}")
    public Integer lockCoupon(Integer couponId) {
        return allUserService.lockCoupon(couponId);
    }

    /**
     * 扣除用户余额
     *
     * @param userId
     * @param amount
     */
    @PostMapping("/deductBalance/{userId}/{amount}")
    public ResponseData deductBalance(@PathVariable("userId") Long userId,
                                      @PathVariable("amount") BigDecimal amount) {
        return allUserService.deductBalance(userId, amount);
    }

    /**
     * 我用来测试pay模块的userApi
     * 别删！！！
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/getUserInfoAPI/{userId}")
    public AllUser getUserInfoAPI(@PathVariable("userId") Long userId) {
        return allUserService.getUserById(userId);
    }
    /**
     * 添加商家钱包余额
     *
     * @param userId
     * @return
     */
    @PostMapping("/increaseBalance/{sellerId}/{amount}")
    public ResponseData increaseBalance(@PathVariable("sellerId") Long sellerId,
                                        @PathVariable("amount") BigDecimal amount) {
        return allUserService.increaseBalance(sellerId, amount);
    }

}
